<!--海外管理-上架-->
<template>
  <div class="page-container">
    <page_breadcrumb :getKeyMethod="init_table_model" @change="change_table_model" />

    <el-form :model="form" ref="form" class="flex_cell flex_col">
      <ex_super_table_page v-bind="option" ref="SuperTablePage" :data="form.tableList" :autoLoad="false">

      </ex_super_table_page>
    </el-form>

    <ex_super_dialog_form ref="formDialogPutaway" :title="$tt('label_putaway_confirm')" v-bind="dialogBindPutaway"
      @afterSubmitSuccess="putawaySuccess">
    </ex_super_dialog_form>

  </div>
</template>

<script>
import superTablePageFunction from '@/mixin/super-table-page-function';
import router_params from '@/mixin/router_params';
import page_table_model_manage from '@/mixin/page_table_model_manage';

export default {
  title: 'title_standard_putaway',
  mixins: [superTablePageFunction, router_params, page_table_model_manage],
  data() {
    return {

      orderData: null,

      putawayId: "",
      putawayCode: "",
      inboundOrderId: "",
      inboundOrderCode: "",
      form: {
        tableList: [],
      },

      option: {
        search: {
          default: { inboundOrderCode: '' },
          model: [

            {
              label: "label_search", key: "inboundOrderCode",
              keylist: [
                { label: 'label_inbound_code', value: 'inboundOrderCode' }, { label: 'label_putaway_code', value: 'putawayCode' },
              ],
            },

          ],
        },
        actionExtra: [
          { label: 'label_putaway_confirm', attrs: { type: "primary" }, click: this.conformPutway },
          // { label: 'label_print_inbound_code', click: this.$noFunction },
          { label: 'label_batch_import', click: this.$noFunction },
        ],
        table: {
          autoPage: false, specialStyle: false,
          attrs: { 'cell-class-name': this.cellClassName, 'span-method': this.objectSpanMethod },
          url: "/wms-api/inbound/WmsInboundOverseasPutawayRpc/selectBoxDetail.json",
          urlDataHandle: this.dataHandle,
          model: this.init_table_model(),
        }
      },
      skuUrlList: [],
      dialogBindPutaway: {
        customClass: 'dialog_auto',
        submitUrl: '/wms-api/inbound/WmsInboundOverseasPutawayRpc/putaway.json',
        submitDataHandle: this.submitPutawayDataHandle,
        form: {
          itemClass: "form_item_big",
          formClass: "form_big_col2",
          inline: true,
          model: [
            { key: 'inboundOrderCode', label: 'label_inbound_code', type: 'text', inputClass: "bold ", },
            { key: 'putawayCode', label: 'label_putaway_code', type: 'text', inputClass: "bold ", },
            { key: 'planBoxNumber', label: 'label_plan_putaway_box_number', type: 'text', inputClass: "bold ", },

            { key: 'planPieceNumber', label: 'label_plan_putaway_number', type: 'text', inputClass: "bold ", },
            { key: 'actualBoxNumber', label: 'label_actual_putaway_box_number', type: 'text', inputClass: "bold ", },
            { key: 'actualPieceNumber', label: 'label_actual_putaway_number', type: 'text', inputClass: "bold ", },
            {
              key: 'items', label: 'label_putaway_sku_specification', itemClass: "form_item_flex_row over_auto", inputClass: " ",
              formType: 'table', 'max-height': 500,
              model: [
                { key: 'boxNo', label: 'label_box_code', 'min-width': 120, 'show-overflow-tooltip': true, },
                { key: 'limitQty', label: 'label_plan_putaway_number', 'width': 120, },

                {
                  key: 'putawayQty', label: 'label_actual_putaway_number', 'width': 120,
                  formatter: (r, c, v) => r.boxDetailLocationList.map(it => it.putawayQty).join(',')
                },
                {
                  key: 'putawayAreaCode', label: 'label_putaway_warehouse_area', 'min-width': 120,
                  formatter: (r, c, v) => r.boxDetailLocationList.map(it => it.putawayAreaCode).join(',')
                },
                {
                  key: 'putawayLocationCode', label: 'label_putaway_warehouse_location', 'min-width': 120,
                  formatter: (r, c, v) => r.boxDetailLocationList.map(it => it.putawayLocationCode).join(',')
                },
                { key: 'putawayUserName', label: 'label_putaway_user', 'min-width': 120, 'show-overflow-tooltip': true, },
              ]
            }
          ],
        }
      },
      formRules: {
        putawayAreaId: {
          type: 'array',
          defaultField: {
            type: "object",
            fields: {
              putawayAreaId: { type: "string", required: true, message: this.$tt('tip_can_no_empty'), }
            },
          }
        },
        putawayLocationId: {
          type: 'array',
          defaultField: {
            type: "object",
            fields: {
              putawayLocationId: { type: "string", required: true, message: this.$tt('tip_can_no_empty'), }
            },
          }
        },
        putawayUserName: { type: "string", required: true, message: this.$tt('tip_can_no_empty'), }
      },
    };
  },


  computed: {

    isPallet: function () {
      return this.orderData && this.orderData.isPallet == 'Y'
    },
    TOB() {
      return this.orderData && this.orderData.bizType == 'TOB'
    },

  },

  methods: {
    getPutTypeList(row) {
      const list = []
      if (!this.TOB) {
        list.push({ label: 'Putaway_SKU', value: 'SKU' })
      }
      if (row._linkBox.every(it => !this.disabledEdit(it))) {
        list.push({ label: 'Putaway_BOX', value: 'BOX' })
      }
      if (this.isPallet && row._linkPallet.every(it => !this.disabledEdit(it))) {
        list.push({ label: 'Putaway_PALLET', value: 'PALLET' })
      }
      return list
    },
    option_table_model() {
      return [
        {
          key: 'putType', label: 'label_putaway_type', 'width': 140,
          render: (h, { row }) => {
            if (this.disabledEdit(row)) {
              return "——"
            } else {
              const typeList = this.getPutTypeList(row)

              return (<ex_select_auto value={row.putType} disabled={typeList.length <= 1}
                type="select" i18n items={typeList} onInput={e => this.changeItemType(e, row)} class="w_fill" />)
            }


          }
        },
        {
          key: 'palletNo', label: 'label_pallet_code', 'min-width': 140,
          if: () => this.isPallet,
        },
        { key: 'boxNo', label: 'label_box_code', 'min-width': 140, },

        { key: 'skuBarcode', label: 'label_sku_code', 'min-width': 120, },
        { key: 'skuName', label: 'label_sku_name', 'min-width': 120, },
        {
          key: 'skuUrl', label: 'label_sku_image', 'width': 120,
          render: (h, { row }) => {
            return (<ex_image_view class="page_table_image" src={row.skuUrl} lazy fit="fill" preview-src-list={this.skuUrlList} />)
          }
        },

        {
          key: 'putawayStatus', label: 'label_putaway_status', 'width': 100,
          formatter: (r, c, v, i) => this.$enumShow(v, "PutawayStatusEnum"),
        },


        { key: 'receivingQty', label: 'label_receiving_number', 'width': 100, },
        { key: 'acceptanceQty', label: 'label_acceptance_number', 'width': 100, },

        { key: 'putawayHasQty', label: 'label_has_putaway_number', 'width': 100, },
        {
          key: 'putawayPallet', label: 'label_putaway_pallet_number', 'min-width': 180, keyShowForce: [true],
          if: () => this.isPallet,
          render: (h, { row, column }) => {
            const value = row[column.property]
            if (row.putType == 'PALLET' && !this.disabledEdit(row)) {
              return (<el-input-number value={value} class="w_fill" min={0} max={1} onInput={e => this.changePutawayPallet(e, row)} />)
            } else {
              return value
            }
          },

        },
        {
          key: 'putawayBox', label: 'label_putaway_box_number', 'min-width': 140, keyShowForce: [true],
          if: () => !this.isPallet,
          render: (h, { row, column }) => {
            if (this.disabledEdit(row)) {
              if (_.isEmpty(row.boxDetailLocationList)) return
              return (<div>{
                row.boxDetailLocationList.map(item =>
                  (<div>【{item.putawayAreaCode}】【{item.putawayLocationCode}】 → (<span class="bold color_success">{item.putawayQty}</span>) → ({this.$formatNameCode(item.putawayUserName, item.putawayUserCode)})</div>))
              }</div>)
            }
            const value = row[column.property]
            if (row.putType == 'BOX' && !this.disabledEdit(row)) {
              return (< el-input-number value={value} class="w_fill" min={0} max={1} onInput={e => this.changePutawayBox(e, row)} />)
            } else {
              return value
            }
          },

        },
        {
          key: 'putawayQty', label: 'label_putaway_number', 'min-width': 170, keyShowForce: [true],
          render: (h, { row, column }) => {
            if (row.putType == 'SKU' && !this.disabledEdit(row)) {
              const list = row.boxDetailLocationList.map((item, index) => {
                const value = item[column.property]

                let button = null
                if (index == 0) {
                  button = (<el-button type='text' class='mg_h2' onClick={e => this.insertRow(row)}
                    disabled={(row.boxDetailLocationList.length >= row.limitQty - row.putawayHasQty)}>{this.$tt('label_split')}</el-button>)
                } else {
                  button = (<el-button type='text' class='mg_h2 button_text_danger' onClick={e => this.removeRow(row, index)}
                  >{this.$tt('label_remove')}</el-button>)
                }
                return (
                  <div class="flex_row_center" key={index}>
                    < el-input-number value={value} class="flex_cell" min={0} max={this.lastPutQty(row, item)}
                      onInput={e => this.changeItemPutawayQty(e, item, row)} />
                    {button}
                  </div>
                )
              })
              return list
            } else {
              return this.getRowPutawayQty(row)
            }
          },
        },
        {
          key: 'recommended', label: 'label_recommend_location', 'width': 170,
          render: (h, { row }) => {

            if (row.recommending) return (<div class="color_info"><i class="el-icon-loading el-icon--left"></i>{this.$tt('tip_search_recommend_location_ing')}</div>)
            if (!row.recommended) return (<div class="color_info">{this.$tt('tip_no_data')}</div>)
            return h('div', row.recommended.map(location => h('div', { class: 'tag_primary mg_v1' }, location.locationCode)))
          }
        },
        {
          key: 'putawayAreaId', label: 'label_putaway_warehouse_area', 'min-width': 200,
          keyShowForce: [true],
          renderHeader: (h, { column }) => {
            return (<div>
              <div>{this.$tt(column.label)}</div>
              <ex_dropdown_auto label='label_unified_select' size='mini' storeData option={{ label: 'labelStr', value: 'id' }}
                url='/wms-api/base/WmsBaseAreaRpc/selectAllLabel.json' onCommand={this.selectAllArea} />
            </div>)
          },
          render: (h, { column, row, index }) => {
            if (this.disabledEdit(row)) return ""
            const rule = row.boxDetailLocationList.some(it => it.putawayQty) ? this.formRules.putawayAreaId : null
            const list =
              row.boxDetailLocationList.map((item, i) => {
                const value = item[column.property]
                const key = `putawayAreaId+${row.boxId}+${row.skuId}+${i}`
                return (
                  <base_area_select key={key} class="w_fill" clearable={false} value={value}
                    onChangeItem={e => this.changeArea(e, row, item)}
                  />
                )
              })
            return (
              <el-form-item
                prop={`tableList.${index}.boxDetailLocationList`}
                rules={rule}
              >
                {list}
              </el-form-item>
            );
          },
        },
        {
          key: 'putawayLocationId', label: 'label_putaway_warehouse_location', 'min-width': 180, keyShowForce: [true],
          render: (h, { column, row, index }) => {
            if (this.disabledEdit(row)) return

            const rule = row.boxDetailLocationList.some(it => it.putawayQty) ? this.formRules.putawayLocationId : null
            const list = row.boxDetailLocationList.map((it, i) => (
              <div>
                <base_location_select key={i} class="w_fill" clearable={false} value={it.putawayLocationId} areaId={it.putawayAreaId}
                  onChangeItem={e => this.changeLocation(e, row, it)} />
              </div>
            ))
            return (
              <el-form-item
                prop={`tableList.${index}.boxDetailLocationList`}
                rules={rule}
              >
                {list}
              </el-form-item>
            );
          },
        },
        {
          key: 'putawayUserId', label: 'label_putaway_user', 'min-width': 180, keyShowForce: [true],
          renderHeader: (h, { column }) => {
            return (<div>
              <div>{this.$tt(column.label)}</div>
              <ex_dropdown_auto label='label_unified_select' size='mini' storeData option={{ label: 'userName', value: 'userId' }}
                url="/ums-api/user/UserInfoRpc/getUserDict.json" onCommand={this.selectAllUser} />
            </div>)
          },
          render: (h, { column, row, index }) => {
            if (this.disabledEdit(row)) return
            const rule = row.boxDetailLocationList.some(it => it.putawayQty) ? this.formRules.putawayUserName : null
            return (
              <el-form-item
                prop={`tableList.${index}.putawayUserName`}
                rules={rule}
              >
                <common_user_select value={row.putawayUserId} class="w_fill" clearable={false} currentLabel={row.putawayUserName}
                  onChangeItem={e => this.changeUser(e, row)} />
              </el-form-item>
            );

          },
        },
      ]
    },
    changeItemType(e, row) {
      this.$set(row, 'putType', e)
      if (!this.orderData) return
      if (!this.disabledEdit(row)) {
        if (row.putType == 'SKU') {
          row._linkPallet.forEach(it => {
            this.$set(it, 'putType', e)
          })
          row._linkBox.forEach(it => {
            this.$set(it, 'putType', e)
          })
        } else {
          this.changeArea(null, row)
          this.changeLocation(null, row)
          if (row.putType == 'BOX') {
            row._linkBox.forEach(it => {
              this.$set(it, 'putType', e)
            })
          } else if (row.putType == 'PALLET') {
            row._linkPallet.forEach(it => {
              this.$set(it, 'putType', e)
            })
          }
        }

      }


    },
    changeType(e) {
      this.type = e
      // if (this.typeBox) {
      //   if (!this.orderData) return
      //   this.getData().forEach(row => {
      //     if (!this.disabledEdit(row)) {
      //       this.changeArea(null, row)
      //       this.changeLocation(null, row)
      //     }
      //   })
      // }
    },
    selectAllArea(e) {
      if (!this.orderData) return
      this.getData().forEach(row => {
        if (!this.disabledEdit(row) && row.boxDetailLocationList) {
          row.boxDetailLocationList.forEach(it => {
            if (it.putawayAreaId != e.id) {
              this.$set(it, 'putawayAreaId', e.id)
              this.$set(it, 'putawayAreaCode', e.code)
            }
          })
        }
      })
    },
    changeArea(e, row, item) {
      if (!e) e = { id: null, code: null }
      if (row.putType == 'PALLET' || row.putType == 'BOX') {
        const _forList = row.putType == 'PALLET' ? row._linkPallet : row._linkBox
        _forList.forEach((it) => {
          it.boxDetailLocationList.forEach(it2 => {
            this.$set(it2, 'putawayAreaId', e.id)
            this.$set(it2, 'putawayAreaCode', e.code)
          })
        })
      } else if (item) {
        this.$set(item, 'putawayAreaId', e.id)
        this.$set(item, 'putawayAreaCode', e.code)

      } else {
        row.boxDetailLocationList.forEach(it2 => {
          this.$set(it2, 'putawayAreaId', e.id)
          this.$set(it2, 'putawayAreaCode', e.code)
        })
      }
    },

    changeLocation(e, row, item) {
      if (!e) e = { id: null, code: null }
      if (row.putType == 'PALLET' || row.putType == 'BOX') {
        const _forList = row.putType == 'PALLET' ? row._linkPallet : row._linkBox
        _forList.forEach((it) => {
          it.boxDetailLocationList.forEach(it2 => {
            this.$set(it2, 'putawayLocationId', e.id)
            this.$set(it2, 'putawayLocationCode', e.code)
          })
        })
      } else if (item) {
        this.$set(item, 'putawayLocationId', e.id)
        this.$set(item, 'putawayLocationCode', e.code)
      } else {
        row.boxDetailLocationList.forEach(it2 => {
          this.$set(it2, 'putawayLocationId', e.id)
          this.$set(it2, 'putawayLocationCode', e.code)
        })
      }

    },

    changePutawayPallet(e, row) {
      row._linkPallet.forEach((it) => {
        this.$set(it, 'putawayBox', e)
        this.$set(it, 'putawayPallet', e)
        it.boxDetailLocationList.forEach((it2, i) => {
          this.$set(it2, 'putawayQty', e && i == 0 ? it.limitQty : 0)
        })
      })
    },

    //修改收货箱数，需要同时对对象内连接的其他箱子进行操作
    changePutawayBox(e, row) {
      row._linkBox.forEach((it) => {
        this.$set(it, 'putawayBox', e)
        it.boxDetailLocationList.forEach((it2, i) => {
          this.$set(it2, 'putawayQty', e && i == 0 ? it.limitQty : 0)
        })

      })
      if (!_.isEmpty(row._linkPallet)) {
        const _pallet = row._linkPallet.some(it => this.getRowPutawayQty(it))
        row._linkPallet.forEach(it => {
          this.$set(it, 'putawayPallet', _pallet ? 1 : 0)
        })
      }
    },
    changeItemPutawayQty(e, item, row) {
      this.$set(item, 'putawayQty', e)
      const _box = row._linkBox.some(it => this.getRowPutawayQty(it))
      row._linkBox.forEach(it => {
        this.$set(it, 'putawayBox', _box ? 1 : 0)
      })
      if (!_.isEmpty(row._linkPallet)) {
        const _pallet = row._linkPallet.some(it => this.getRowPutawayQty(it))
        row._linkPallet.forEach(it => {
          this.$set(it, 'putawayPallet', _pallet ? 1 : 0)
        })
      }
    },

    getRowPutawayQty(row) {
      return _.reduce(row.boxDetailLocationList, (sum, v) => sum + v.putawayQty, 0)
    },


    init_data_default(into_params) {

      let params = into_params
      let search = params

      if (!_.isEmpty(search)) {

        this.inboundOrderCode = ""
        this.inboundOrderId = ""
        this.$refs['SuperTablePage'].setSearchData(Object.assign({}, this.$refs['SuperTablePage'].getSearchData(), search))
        let _keys = Object.keys(search)
        this.option.search.model.forEach(it => {
          if (it.keylist) {
            let _new_key = _.head(_.intersection(it.keylist.map(_k => _k.value), _keys))
            if (_new_key) it.key = _new_key
          }
        })
        this.$nextTick(() => {
          this.$refs['SuperTablePage'].loadDataForSearch()
        })
      }
    },

    changeUser(e, row) {
      if (!e) e = { userId: null, userCode: null, userName: null }
      const _forList = [row]
      _forList.forEach((it) => {
        this.$set(it, "putawayUserId", e.userId)
        this.$set(it, "putawayUserCode", e.userCode)
        this.$set(it, "putawayUserName", e.userName)
      })

    },

    selectAllUser(e) {
      if (!this.orderData) return
      this.orderData.boxDetailList.forEach(it => {
        if (!this.disabledEdit(it)) {
          this.$set(it, 'putawayUserId', e.userId)
          this.$set(it, 'putawayUserCode', e.userCode)
          this.$set(it, 'putawayUserName', e.userName)
        }
      })
    },

    isHasAcceptance(row) {
      return row.acceptanceStatus == 'ACCEPTANCE_COMPLETED'
    },
    isBoxReceiving(row) {
      return row.boxReceivingStatus == 'RECEIVING_COMPLETED'
    },
    isBoxPutaway(row) {
      return row.boxPutawayStatus == 'PUTAWAY_COMPLETED'
    },
    isHasReceiving(row) {
      return row.receivingStatus == 'RECEIVING_COMPLETED'
    },
    isHasPutaway(row) {
      return row.putawayStatus == 'PUTAWAY_COMPLETED'
    },
    disabledEdit(row) {
      return this.isHasPutaway(row) || !this.isHasReceiving(row) || (!this.TOB && !this.isHasAcceptance(row) && !this.$loginUser.ifElse英威特) || (this.isHasAcceptance(row) && row.acceptanceQty == 0)
    },
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (this.disabledEdit(row)) {
        return 'tableCell_disabled'
      }
      return 'tableCell_noHoverLight'
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (this.disabledEdit(row)) {
        if (['putawayBox'].includes(column.property)) {
          return { rowspan: 1, colspan: 6 }
        }
        if (['putawayQty', 'recommended', 'putawayAreaId', 'putawayLocationId', 'putawayUserId'].includes(column.property)) {
          return { rowspan: 1, colspan: 0 }
        }
      }
      if (['putType', 'putawayAreaId', 'putawayLocationId',].includes(column.property)) {
        if (row.putType == 'BOX') {
          return { rowspan: row.rowspanBox, colspan: 1 }
        } else if (row.putType == 'PALLET') {
          return { rowspan: row.rowspanPallet, colspan: 1 }
        }
      }
      if (['boxNumber', 'quantity_box', 'boxNo', 'receivingBox', 'putawayBox'].includes(column.property)) {
        return { rowspan: row.rowspanBox, colspan: 1 }
      } else if (['receivingPallet', 'putawayPallet', 'palletNo'].includes(column.property)) {
        return { rowspan: row.rowspanPallet, colspan: 1 }
      }
      // if (['putawayAreaId', 'putawayLocationId',].includes(column.property)) {
      //   if (row.putType == 'BOX') {
      //     return { rowspan: row.putType == 'BOX' ? row.rowspanBox : row.rowspanPallet, colspan: 1 }
      //   }
      // }
    },
    dataHandle(res) {
      if (!res.data || !res.data.inboundOrderCode || _.isEmpty(res.data.boxDetailList)) {
        this.orderData = null
        this.$message.warning(this.$tt("tip_search_no_data"))
        return []
      }
      this.putawayCode = res.data.taskCode ? res.data.taskCode : ''
      this.putawayId = res.data.taskId ? res.data.taskId : ''
      this.inboundOrderId = res.data.inboundOrderId
      this.inboundOrderCode = res.data.inboundOrderCode

      this.orderData = res.data


      let putType = null
      if (this.isPallet) {
        putType = 'PALLET'
      } else if (this.TOB) {
        putType = 'BOX'
      } else {
        putType = 'SKU'
      }

      const _list = res.data.boxDetailList
      _list.sort((a, b) => {
        if (this.isPallet) {
          if (a.palletNo == b.palletNo) { }
          else if (a.palletNo > b.palletNo) { return 1 }
          else if (a.palletNo < b.palletNo) { return -1 }
        }
        if (a.boxNo == b.boxNo) { return 0 }
        else if (a.boxNo > b.boxNo) { return 1 }
        else if (a.boxNo < b.boxNo) { return -1 }
      })
      this.skuUrlList = _list.map(it => it.skuUrl)
      let currentUser = this.$loginUser
      if (!currentUser) currentUser = { userId: null, userCode: null, userName: null, }
      _list.forEach((row, i) => {
        row.skipAcceptance = res.data.skipAcceptance
        //验收后使用验收数量作为限制
        row.limitQty = this.isHasAcceptance(row) ? row.acceptanceQty : row.receivingQty
        // this.$set(row, 'boxDetailLocationList', [{ putawayQty: row.limitQty, putawayAreaId: null, putawayAreaCode: null, putawayLocationId: null }])

        row.error = {}
        row.putawayAreaId = null
        row.putawayLocationId = null



        row._linkBox = _list.filter(it2 => it2.boxNo == row.boxNo)
        //验收后使用验收数量作为限制
        row.limitQty = row.expectPutawayQty//this.isHasAcceptance(row) ? row.acceptanceQty : row.receivingQty
        if (row.rowspanBox == undefined) {
          row._linkBox.forEach(it2 => it2.rowspanBox = 0)
          row.rowspanBox = row._linkBox.length
        }

        row._linkPallet = _list.filter(it2 => it2.palletNo == row.palletNo)
        if (row.rowspanPallet == undefined) {
          row._linkPallet.forEach(it2 => it2.rowspanPallet = 0)
          row.rowspanPallet = row._linkPallet.length
        }

        row.putawayHasQty = row.putawayQty
        row.receivingBox = this.isBoxReceiving(row) ? 1 : 0
        if (!_.isEmpty(row._linkPallet)) {
          row.receivingPallet = row._linkPallet.some(row => this.isBoxReceiving(row)) ? 1 : 0
        }
        if (this.disabledEdit(row)) {
          this.$set(row, 'putawayBox', this.isBoxPutaway(row) ? 1 : 0)
          if (!_.isEmpty(row._linkPallet)) {
            this.$set(row, 'putawayPallet', row._linkPallet.some(row => this.isBoxPutaway(row)) ? 1 : 0)
          }
        } else {
          this.$set(row, 'putawayPallet', row.receivingPallet)
          this.$set(row, 'putawayBox', row.receivingBox)
          row.putawayQty = row.limitQty
        }

        if (!this.disabledEdit(row)) {
          this.$set(row, 'putawayUserId', currentUser.userId)
          this.$set(row, 'putawayUserCode', currentUser.userCode)
          this.$set(row, 'putawayUserName', currentUser.userName)
          const typeList = this.getPutTypeList(row)
          this.$set(row, 'putType', _.head(typeList).value)
          this.$set(row, 'boxDetailLocationList', [{ putawayQty: row.limitQty, putawayAreaId: null, putawayLocationId: null }])
        }

      })
      // this.orderData.boxDetailList = _list
      // this.refresh_table_visible()
      this.form.tableList = _list
      this.refreshRecommend()
      // console.log(_list)
      //查找推荐库位
      return _list
    },

    refreshRecommend() {
      const recommendParam = []
      const recommendList = this.form.tableList.filter(row => !this.disabledEdit(row))
      recommendList.forEach(row => this.$set(row, 'recommending', true))
      if (!_.isEmpty(recommendList)) {
        const skus = recommendList.filter(row => row.putType == 'SKU')
        if (!_.isEmpty(skus)) {
          _.forOwn(_.groupBy(skus, row => row.boxNo), (v, k) => {
            recommendParam.push({
              boxMarker: k,
              putawayType: 'SKU',
              skuList: v.map(row => {
                return {
                  skuId: row.skuId,
                  skuMarker: k,
                  putawayQty: (Number(row.limitQty) - Number(row.putawayHasQty)),
                }
              })
            })
          })
        }
        // recommendParam.push({
        //   boxMarker: k,
        //   putawayType: "SKU",
        //   skuList: recommendList.filter(row => row.putType == 'SKU').map(row => {
        //     return {
        //       skuId: row.skuId,
        //       skuMarker: row.skuId,
        //       putawayQty: (Number(row.limitQty) - Number(row.putawayHasQty)),
        //     }
        //   })
        // })
        const boxs = recommendList.filter(row => row.putType == 'BOX')
        if (!_.isEmpty(boxs)) {
          _.forOwn(_.groupBy(boxs, row => row.boxNo), (v, k) => {
            recommendParam.push({
              boxMarker: k,
              putawayType: 'BOX',
              skuList: v.map(row => {
                return {
                  skuId: row.skuId,
                  skuMarker: k,
                  putawayQty: (Number(row.limitQty) - Number(row.putawayHasQty)),
                }
              })
            })
          })
        }
        const pallets = recommendList.filter(row => row.putType == 'PALLET')
        if (!_.isEmpty(pallets)) {
          _.forOwn(_.groupBy(pallets, row => row.palletNo), (v, k) => {
            recommendParam.push({
              boxMarker: k,
              putawayType: 'PALLET',
              skuList: v.map(row => {
                return {
                  skuId: row.skuId,
                  skuMarker: k,
                  putawayQty: (Number(row.limitQty) - Number(row.putawayHasQty)),
                }
              })
            })
          })
        }
        this.recommendLocation(recommendParam, recommendList)
      }
    },
    recommendLocation(boxList, recommendList) {
      this.$ajax({
        url: "/wms-api/base/WmsBasePutawayStrategyRpc/recommendLocation.json",
        method: 'post', type: 'json',
        // loading: "正在查找推荐库位",
        data: { boxList: boxList },
        success: (res) => {
          if (res && res.data && res.data.boxList) {
            res.data.boxList.forEach(box => {

              const palletType = box.putawayType == 'PALLET'
              const box_detail = palletType ? this.orderData.boxDetailList.filter(it => it.palletNo == box.boxMarker) : this.orderData.boxDetailList.filter(it => it.boxNo == box.boxMarker)
              box.skuList.forEach(sku => {
                const item = _.find(box_detail, it => it.skuId == sku.skuId)
                if (item) {
                  this.$set(item, 'recommended', sku.recommendedLocationList)
                }
              })
            })
          }
        },
        complete: () => {
          recommendList.forEach(row => this.$set(row, 'recommending', false))
        }
      })

    },
    lastPutQty(row, item) {
      let sumPutQty = row.boxDetailLocationList.filter(it => it != item)
        .reduce((sum, it) => this.$math_add(sum, it.putawayQty), 0)
      return row.limitQty - sumPutQty - row.putawayHasQty
    },
    insertRow(row) {
      if (row.boxDetailLocationList.length >= (row.limitQty - row.putawayHasQty)) return
      row.boxDetailLocationList.push({ putawayQty: 0, putawayAreaId: null, putawayLocationId: null })
    },
    removeRow(row, i) {
      row.boxDetailLocationList.splice(i, 1)
    },

    conformPutway() {
      if (_.isEmpty(this.inboundOrderCode)) {
        return this.$message.error(this.$tt('tip_please_first_search'))
      }
      let _hasList = this.getData().filter(it => !this.disabledEdit(it))

      let _list = _hasList.filter(it => it.boxDetailLocationList.some(b => b.putawayQty))

      let _putawayQty = _.reduce(_.flatMap(_list, it => it.boxDetailLocationList), (sum, it) => sum + it.putawayQty, 0)
      if (_putawayQty == 0) {
        return this.$message.error(this.$tt('tip_putaway_content_no_empty'))
      }

      this.$refs.form.validate((valid, obj) => {
        if (valid) {
          this.$refs.formDialogPutaway.show({
            inboundOrderId: this.orderData.inboundOrderId,
            inboundOrderCode: this.orderData.inboundOrderCode,
            putawayId: this.orderData.putawayId,
            putawayCode: this.orderData.putawayCode,
            // putawayType: this.type,
            planBoxNumber: _.uniqBy(_hasList, 'boxNo').length,
            planPieceNumber: _.reduce(_hasList, (sum, v) => sum + v.limitQty, 0),
            actualBoxNumber: _.uniqBy(_list, 'boxNo').length,
            actualPieceNumber: _putawayQty,
            items: _.cloneDeep(_list).filter(it => {
              it.boxDetailLocationList = it.boxDetailLocationList.filter(d => d.putawayQty > 0)
              return !_.isEmpty(it.boxDetailLocationList)
            }),
          }, true,)
        } else {
          this.$message.error(this.$t('form_validate_error'))
          return false;
        }
      });





    },
    submitPutawayDataHandle(data) {
      let urldata = {
        inboundOrderId: data.inboundOrderId
      }
      if (data.putawayId) urldata.putawayId = data.putawayId
      urldata.boxDetailList = data.items.map(it => {
        return {
          boxId: it.boxId,
          boxNo: it.boxNo,
          putawayType: data.putawayType,
          boxDetailId: it.boxDetailId,
          // putawayQty: it.putawayQty,
          // putawayAreaId: it.putawayAreaId,
          // putawayAreaCode: it.putawayAreaCode,
          // putawayLocationId: it.putawayLocationId,
          // putawayLocationCode: it.putawayLocationCode,

          putawayUserId: it.putawayUserId,
          putawayUserCode: it.putawayUserCode,
          putawayUserName: it.putawayUserName,

          boxDetailLocationList: it.boxDetailLocationList,
        }
      })
      return urldata
    },
    putawaySuccess() {
      this.reload()
      this.$emitPage("standard>inbound_manage", "reload")
      this.$emitPage("overseas=>putaway_task", "reload")
    },

  }
}

</script>
<style></style>
